package com.hyfd.service.mp;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hyfd.common.BaseJson;
import com.hyfd.dao.mp.AgentDataDiscountDao;
import com.hyfd.dao.mp.DataPkgDao;
import com.hyfd.dao.mp.PhoneSectionDao;
import com.hyfd.dao.mp.ProviderDao;
import com.hyfd.service.BaseService;

@Service
public class DataChargeSer extends BaseService {

	public Logger log = Logger.getLogger(this.getClass());

	@Autowired
	private PhoneSectionSer phoneSectionSer;
	@Autowired
	DataPkgDao dataPkgDao;
	@Autowired
	ProviderDao providerDao;
	@Autowired
	AgentDataDiscountDao agentDataDiscountDao;
	@Autowired
	PhoneSectionDao phoneSectionDao;

	/**
	 * 检测输入手机号的信息
	 * */
	public String batchCheckPhone(HttpServletRequest req) {
		String str = "";
		try {
			Map<String, Object> map = getMaps(req);
			String numberMeg = (String) map.get("numberMeg");
			Map<String, Object> agent = agentGetByUserId();
			String agentName = (String) agent.get("name");
			String agentId = (String) agent.get("id");
			String dataType = (String) map.get("dataType");
			String[] mobileMeg = numberMeg.split(",");
			int count = mobileMeg.length;// 前台传来手机号的个数
			Map<String, Object> checkPhoneMessage = phoneSectionSer.checkPhoneMessage(mobileMeg);// 检测前台传入的手机号
			List<String> phoneMessage = (List<String>) checkPhoneMessage.get("phoneMessage");// 有效的手机号信息
			Set<String> faceValue = (Set<String>) checkPhoneMessage.get("faceValue");
			int valid = phoneMessage.size();// 有效的手机号个数
			int inValid = count - valid;// 无效的手机号个数
			Map<String, Object> distributionByData = phoneSectionSer.distributionByData(phoneMessage);//号码信息分类，放入各自运营商下
			Map<String, Object> result = new HashMap<String, Object>();
			Map<String, Object> data = new HashMap<String, Object>();
			for (Map.Entry<String, Object> entry : distributionByData.entrySet()) {
				String providerId = entry.getKey();// 运营商Id
				String providerName = providerDao.getNameById(providerId);
				List<String> value = (List<String>) entry.getValue();
				String res = getTotal(value, dataType, providerId, agentId);
				if(res!=""){
					data.put(providerName, res);
				}
			}
			result.put("phoneMeg", data);
			result.put("phone", phoneMessage);
			result.put("agentName", agentName);
			result.put("count", count);
			result.put("valid", valid);
			result.put("inValid", inValid);
			str = BaseJson.mapToJson(result);
		} catch (Exception e) {
			getMyLog(e, log);
		}
		return str;
	}

	public String getTotal(List<String> val, String dataType, String providerId,String agentId) {
		String result="";
		try {
			Map<String, Integer> m = new HashMap<String, Integer>();// 生成卡包和卡包对应的面值
			List<String> valueList = new ArrayList<String>();
			double total = 0.0;
			for (String phoneMeg : val) {
				String[] meg = phoneMeg.split("-");
				String value = meg[1];
				valueList.add(value);
				double price = checkPhone(phoneMeg, dataType, providerId, agentId);
				total += price;
			}
			if(total!=0.0){
				for (String i : valueList) {
				    if (m.get(i) == null) {
				        m.put(i, 1);
				    } else {
				        m.put(i, m.get(i) + 1);
				    }
				}
				for(Entry<String, Integer> entry : m.entrySet()){
					String value = entry.getKey();
					Integer count = entry.getValue();
					String meg="充值<font color=\"red\">"+value+"兆</font>的手机号有<font color=\"red\">"+count+"个</font>  ";
					result=result+meg;
				}
				result=result+"  总价为<font color=\"red\">"+total+"元</font>";
			}
		} catch (Exception e) {
			getMyLog(e, log);
		}
		return result;
	}

	/**
	 * 获取号码折扣
	 * */
	public double checkPhone(String phoneMeg, String dataType,String providerId, String agentId) {
		double discountPrice = 0.0;
		try {
			String[] split = phoneMeg.split("-");
			String phone = split[0];
			String value = split[1];
			String provinceCode = split[2];
			if (dataType.equals("2")) {
				provinceCode = "全国";
			}
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("providerId", providerId);
			data.put("value", value);
			data.put("dataType", dataType);
			data.put("provinceCode", provinceCode);
			Map<String, Object> dataPkg = dataPkgDao.getDataPkgByProIdAndPrice(data);
			if (dataPkg != null) {
				String dataPkgId = (String) dataPkg.get("id");
				BigDecimal dataPrice = (BigDecimal) dataPkg.get("price");
				double pkgPrice = dataPrice.doubleValue();
				if (dataPkgId != null && dataPkgId != "") {
					Map<String, Object> p = new HashMap<String, Object>();
					p.put("agentId", agentId);
					p.put("providerId", providerId);
					p.put("dataPkgId", dataPkgId);
					p.put("provinceCode", provinceCode);
					Map<String, Object> agentDataDiscount = agentDataDiscountDao
							.agentDataDiscountGet(p);
					if (agentDataDiscount != null) {
						String discount = agentDataDiscount.get("discount")
								+ "";
						double dis = Double.parseDouble(discount);
						BigDecimal b1 = new BigDecimal(pkgPrice);
						BigDecimal b2 = new BigDecimal(dis);
						discountPrice = new Double(b1.multiply(b2)
								.doubleValue());
					}
				}
			}
		} catch (Exception e) {
			getMyLog(e, log);
		}
		return discountPrice;
	}
	
	/**
	 * 根据手机号查询号段、流量包信息
	 * */
	public String sectionAndDataPkgGet(HttpServletRequest req) {
		String str = null;
		try {
			Map<String, Object> m = getMaps(req);
			String phone = (String) m.get("phone");
			String dataType = (String) m.get("dataType");
			// 获取手机号相关信息
			String section = (phone.length() == 13) ? phone.substring(0, 5)
					: phone.substring(0, 7);// 获取号段
			Map<String, Object> sectionMessage = phoneSectionDao
					.selectBySection(section);
			if (sectionMessage != null) {
				Map<String, Object> agent = agentGetByUserId();
				String agentId = (String) agent.get("id");
				m.put("agentId", agentId);
				String agentName = (String) agent.get("name");
				sectionMessage.put("agentName", agentName);
				String providerId = (String) sectionMessage.get("provider_id");
				String providerName = providerDao.getNameById(providerId);
				sectionMessage.put("providerName", providerName);
				m.put("providerId", providerId);
				String provinceCode="";
				if(dataType.equals("1")){
					provinceCode = (String) sectionMessage.get("province_code");
					m.put("provinceCode", provinceCode);
					List<Map<String, Object>> pkgIdList = agentDataDiscountDao.getAgentDataDiscountPkgList(m);
					sectionMessage.put("dataPkgMessage", pkgIdList);
				}if(dataType.equals("2")){
					List<Map<String, Object>> pkgIdList = agentDataDiscountDao.getAgentDataDiscountPkgList(m);
					sectionMessage.put("dataPkgMessage", pkgIdList);
				}
			}
			str = BaseJson.mapToJson(sectionMessage);
		} catch (Exception e) {
			getMyLog(e, log);
		}
		return str;
	}
}
